<?php
namespace app\admin\controller;

use app\common\model\Collect as CollectModel;
use app\common\model\Category as CategoryModel;
use app\common\controller\AdminBase;
use think\facade\Cache;
use think\facade\Config;

/**
 * 采集管理
 * Class Collect
 * @package app\admin\controller
 */
class Collect extends AdminBase
{
    protected $collect_model;
    protected $category_model;

    protected function initialize()
    {
        parent::initialize();
        $this->collect_model  = new CollectModel();
        $this->category_model = new CategoryModel();

        $category_level_list = $this->category_model->getLevelList();
        $this->assign('category_level_list', $category_level_list);
    }

    /**
     * 內容管理
     * @param string $keyword 关键词
     * @param int    $page
     * @return mixed
     */
    public function index( $keyword = '', $page = 1)
    {
        $collect_list  = $this->collect_model->order('sort DESC,id desc')->paginate(20, false, ['page' => $page]);
        return $this->fetch('index', ['collect_list' => $collect_list, 'keyword' => $keyword]);
    }

    /**
     * apica 
     * @param array $pp
     * @return mixed|void
     */
    public function api($pp = [])
    {
        $param = input();
        if (!empty($pp)) {
            $param = $pp;
        }

        //分类
        $type_list = model('category')->getTypeList();
        $this->assign('type_list', $type_list);

        if (!empty($param['pg'])) {
            $param['page'] = $param['pg'];
            unset($param['pg']);
        }

        return $this->vod($param);
    }

    /**
     * 绑定分类
     */
    public function bind()
    {
        $ids = $this->request->param('ids');
        $col = $this->request->param('col');
        $val = $this->request->param('val'); //分类id

        if(!empty($col)){
            $config = Config::pull('bind');
            $config[$col] = intval($val);

            $data = [];
            $data['id'] = $col;
            $data['st'] = 0;
            $data['local_type_id'] = $val;
            $data['local_type_name'] = '';

            if(intval($val) > 0){
                $data['st'] = 1;
                $type_list = model('category')->getTypeList();
                $data['local_type_name'] = $type_list[$val]['name'];
            }

            $res = arr2file( APP_PATH .'config/bind.php', $config);
            if($res === false){
                return $this->error('保存失败，请重试!');
            }
            return $this->success('保存成功!',null, $data);
        }
        return $this->error('参数错误');
    }

    /**
     * 视频采集
     * @param $param
     * @return mixed|void
     */
    public function vod($param)
    {
        if($param['ac'] != 'list'){
            Cache::set('collect_break_vod', url('collect/api').'?'. http_build_query($param) );
        }

        $result = model('collect')->vod($param);

        if($result['code'] > 1){
            return $this->error($result['msg']);
        }

        if($param['ac'] == 'list'){

            $bind_list = Config::pull('bind');
            $type_list = model('category')->getTypeList();

            foreach($result['type'] as $k => $v){
                $key = $param['cjflag'] . '_' . $v['type_id'];
                $result['type'][$k]['isbind'] = 0;
                $local_id = 0;
                if (array_key_exists($key,$bind_list)) {
                    $local_id = intval($bind_list[$key]);
                }

                $type_name = "未知分类";
                if($local_id > 0){
                    $result['type'][$k]['isbind'] = 1;
                    $result['type'][$k]['local_type_id'] = $local_id;
                    if (array_key_exists($local_id,$type_list)) {
                        $type_name = $type_list[$local_id]['name'];
                    }
                }
                $result['type'][$k]['local_type_name'] = $type_name;
            }

            $this->assign('page',$result['page']);
            $this->assign('type',$result['type']);
            $this->assign('list',$result['data']);

            $this->assign('total',$result['page']['recordcount']);
            $this->assign('page',$result['page']['page']);
            $this->assign('limit',$result['page']['pagesize']);

            $param['page'] = $result['page']['page'];
            $param['limit'] = $result['page']['pagesize'];
            $this->assign('param',$param);

            $param['page'] = '{page}';
            $param['limit'] = '{limit}';
            $this->assign('param_str',http_build_query($param)) ;

            return $this->fetch('vod');
        }else {
            mac_echo('<style type="text/css">body{font-size:12px;color: #333333;line-height:21px;}span{font-weight:bold;color:#FF0000}</style>');
            model('Collect')->vod_data($param,$result);
        }
    }


    /**
     * 测试采集
     * @return mixed
     */
    public function test()
    {
        $param = $this->request->only(['cjurl', 'cjflag', 'ac', 'collect_type']);
        $result = model('collect')->vod($param);
        $this->echoJson($result);
    }

    /**
     * 添加內容
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存內容
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Collect');
            $data["jiexi_urls"] =  htmlspecialchars_decode($data["jiexi_urls"]);

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->collect_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑內容
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $info = $this->collect_model->find($id);
        return $this->fetch('edit', ['info' => $info]);
    }

    /**
     * 更新內容
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Collect');
            $data["jiexi_urls"] =  htmlspecialchars_decode($data["jiexi_urls"]);

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->collect_model->allowField(true)->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除內容
     * @param int   $id
     * @param array $ids
     */
    public function delete($id = 0, $ids = [])
    {
        $id = $ids ? $ids : $id;
        if ($id) {
            if ($this->collect_model->destroy($id)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的內容');
        }
    }

    /**
     * 清空采集內容
     * @param int   $id
     * @param array $ids
     */
    public function delete_content($id = 0, $ids = [])
    {
        $info = $this->collect_model->find($id);
        $list = model("vod")->select();

        foreach ($list as $item) {

            $vod_play_from = explode("$$$",$item['vod_play_from']);
            $index = array_search($info['collect_tag'],array_values($vod_play_from));

            if ($index !== false) {
                $vod_play_note = explode("$$$",$item['vod_play_note']);
                $vod_play_url = explode("$$$",$item['vod_play_url']);

                unset($vod_play_from[$index]);
                unset($vod_play_note[$index]);
                unset($vod_play_url[$index]);

                $data['vod_play_from'] = join('$$$',$vod_play_from);
                $data['vod_play_note'] = join('$$$',$vod_play_note);
                $data['vod_play_url'] = join('$$$',$vod_play_url);

                model("vod")->save($data,["id" => $item['id']]);
            }


        }

        $this->success('删除成功');
    }

    /**
     * 內容审核状态切换
     * @param array  $ids
     * @param string $type 操作类型
     */
    public function toggle($ids = [], $type = '')
    {
        $data   = [];
        $status = $type == 'audit' ? 1 : 0;

        if (!empty($ids)) {
            foreach ($ids as $value) {
                $data[] = ['id' => $value, 'status' => $status];
            }
            if ($this->article_model->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('请选择需要操作的內容');
        }
    }
}